import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_client_sse/constants/sse_request_type_enum.dart';
import 'package:happy_elf_app/apis/home.dart';
import 'package:happy_elf_app/apis/user.dart';
import 'package:happy_elf_app/store/config.dart';
import 'package:happy_elf_app/store/home.dart';
import 'package:happy_elf_app/utils/adaption.dart';
import 'package:happy_elf_app/utils/color.dart';
import 'package:happy_elf_app/utils/globalKey.dart';
import 'package:happy_elf_app/widgets/Toast/index.dart';
import 'package:happy_elf_app/widgets/headerBack/index.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;
import 'package:flutter_client_sse/flutter_client_sse.dart';

class TaggetSet extends StatefulWidget {
  const TaggetSet({
    Key? key,
    this.callback,
  }) : super(key: key);

  final Function? callback;

  @override
  State<TaggetSet> createState() => _TaggetSetState();
}

class _TaggetSetState extends State<TaggetSet>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  // PageController 用于控制滑动
  late PageController _slideController;
  // 记录当前滑动到的页码（用于计算中间项样式）
  double _currentSlidePage = 0;
  TextEditingController AIController = TextEditingController();
  var dialogState;
  late FocusNode _focusNode;
  final HomeDataProvider = Provider.of<HomeData>(
    Global.navigatorKey.currentContext!,
    listen: false,
  );

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () async {
      getTypeList();
      enter('目标设定');
    });
    _controller = AnimationController(vsync: this);
    // viewportFraction：控制单个item显示的宽度比例（0.7表示item占屏幕宽度的70%，留出空间显示边缘项）
    _slideController = PageController(
      initialPage: 0, // 初始显示第一个item
      viewportFraction: 0.5,
    )..addListener(() {
        // 监听滑动，实时更新当前页码（用于动态样式计算）
        setState(() {
          _currentSlidePage = _slideController.page ?? 0;
        });
      });
    _focusNode = FocusNode();
    // 初始化语音识别
  }

  @override
  void dispose() {
    _controller.dispose();
    _slideController.dispose();
    _focusNode.dispose();
    leave('目标设定');
    _speech.stop();
    super.dispose();
  }

  List dataList = []; // 目标列表
  List setList = []; // 目标内容列表
  List colorList = [
    '#ecddfc',
    '#fdd6da',
    '#ecddfc',
    '#fdd6da',
    '#ecddfc',
    '#fdd6da',
    '#EFFFF5',
    '#FFFFEF',
    '#FFEADC',
    '#F3EFFF',
    '#ffe3d2',
    '#F9CFCF',
    '#ecddfc',
    '#fdd6da'
  ];
  int checkStep = 0; // 0是8选1，1是目标设定2
  int active = 0; // 点击选中
  int _selectedSlideItem = 0;
  final TextEditingController _textEditingController = TextEditingController();
  List _conversation = [];
  final ScrollController _scrollController = ScrollController();
  bool _isBottomSheetOpen = false;
  stt.SpeechToText _speech = stt.SpeechToText();
  Map enterTimes = {};
  int durationSec = 0; // 秒数

  void getTypeList() async {
    var res = await Home().getType();
    if (res['code'] == 200) {
      setState(() {
        dataList = res['data'];
      });
    }
    print('/////$res');
  }

  void getContent() async {
    var res = await Home().getTypeContent(active);
    if (res['code'] == 200) {
      print('获取目标$res');
      List dataList = (res['data'] as List).map((item) {
        item['color'] = getBGC();
        return item;
      }).toList();
      setList = dataList;
      setState(() {});
    }
  }

  Widget dataItem(item) {
    return GestureDetector(
      onTap: () {
        setState(() {
          active = item['id'];
        });
      },
      child: Stack(children: [
        Positioned(
          top: 85,
          child: Container(
            width: 258.px,
            padding: EdgeInsets.symmetric(vertical: 5.px),
            alignment: Alignment.center,
            decoration: BoxDecoration(
                color: hexColor(active == item['id'] ? '#E9614D' : '#ffffff'),
                border: Border.all(width: 1.px, color: hexColor('#cccccc')),
                borderRadius: BorderRadius.circular(10.px)),
            child: Text(
              item['name'],
              style: TextStyle(
                  fontSize: 14,
                  color:
                      hexColor(active == item['id'] ? '#ffffff' : '#000000')),
            ),
          ),
        ),
        SizedBox(
          height: 90,
          child: item['url'] != null
              ? Image.network(
                  item['url'].trim(),
                  errorBuilder: (context, error, stackTrace) =>
                      const Icon(Icons.error),
                )
              : Container(),
        ),
      ]),
    );
  }

  // 打开底部抽屉
  void _openBottomSheet() {
    setState(() {
      _isBottomSheetOpen = true;
      AIController.text = '';
      _conversation = [];
      _sendMessage();
    });

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setState) {
            dialogState = setState;
            return Container(
              margin: const EdgeInsets.symmetric(horizontal: 24),
              padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).viewInsets.bottom, // 适配键盘高度
              ),
              child: Container(
                height: MediaQuery.of(context).size.height * 0.5,
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                    color: hexColor('#ffffff'),
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(20.px),
                      topRight: Radius.circular(20.px),
                    )),
                child: Column(
                  children: [
                    GestureDetector(
                      child: Image.asset(
                        'lib/assets/images/home/down.png',
                        width: 16,
                        height: 16,
                      ),
                      onTap: () {
                        _isBottomSheetOpen = false;
                      },
                    ),
                    const Divider(height: 24),

                    // 对话列表
                    Expanded(
                      child: ListView.builder(
                        controller: _scrollController,
                        itemCount: _conversation.length,
                        itemBuilder: (context, index) {
                          // 对话项布局（不变）
                          final item = _conversation[index];
                          final isAI = item['role'] == 'ai';
                          return Padding(
                            padding: const EdgeInsets.symmetric(vertical: 8),
                            child: Align(
                              alignment: isAI
                                  ? Alignment.centerLeft
                                  : Alignment.centerRight,
                              child: ConstrainedBox(
                                constraints: BoxConstraints(
                                  maxWidth:
                                      (MediaQuery.of(context).size.width - 48) *
                                          0.7,
                                ),
                                child: Container(
                                  padding: const EdgeInsets.all(12),
                                  decoration: BoxDecoration(
                                    color: isAI
                                        ? Colors.grey[200]
                                        : Colors.blue[100],
                                    borderRadius: BorderRadius.circular(12),
                                  ),
                                  child: Text(item['content']!),
                                ),
                              ),
                            ),
                          );
                        },
                      ),
                    ),

                    // 输入区域
                    inputBuild(296),
                    SizedBox(height: 24),
                  ],
                ),
              ),
            );
          },
        );
      },
    ).whenComplete(() {
      setState(() {
        _isBottomSheetOpen = false;
        _conversation.clear();
        _textEditingController.clear();
      });
    });
  }

  // 页面进入
  void enter(String pageName) {
    durationSec = DateTime.now().millisecondsSinceEpoch;
    _sendEvent(pageName, "enter");
  }

  // 页面离开
  void leave(String pageName) {
    if (durationSec != 0) {
      final time =
          ((DateTime.now().millisecondsSinceEpoch - durationSec)).round();
      _sendEvent(pageName, "leave", time: time);
    }
  }

  Future<void> _sendEvent(String pageName, String type, {int? time}) async {
    Map data = {
      "pageName": pageName,
      "eventType": type,
      if (time != null) "duration": time
    };
    var res = await User().report(data);
    print('上报时间$res');
    if (res['code'] == 200) {}
  }

  // 滚动到最新消息
  void _scrollToBottom() {
    if (_scrollController.hasClients) {
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  // 发送消息
  void _sendMessage() async {
    final value = AIController.text.trim();
    String type = _isBottomSheetOpen ? 'ai' : 'type';
    if (type == 'ai') {
      setState(() {
        _textEditingController.clear();
      });

      // 模拟AI思考后回复
      Future.delayed(const Duration(seconds: 1), () async {
        dialogState(() {});
        _conversation.add({'role': 'ai', 'content': ''});
        dialogue(value);
      });
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _scrollToBottom();
      });
    } else {
      print('_selectedSlideItem${setList[_selectedSlideItem]}');
      if (value != '') {
        // 改变目标内容
        var res = await Home().changeContent(
            {'id': setList[_selectedSlideItem]['id'], 'content': value});
        _focusNode.unfocus();
        if (res['code'] == 200) {
          setList[_selectedSlideItem]['content'] = value;
          setState(() {});
        }
      } else {
        Toast.show(context: context, message: '请输入你的目标');
      }
    }
  }

  Future getCookie() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    // 直接获取字符串，不存在则返回空字符串
    return prefs.getString('cookie') ?? '';
  }

  void dialogue(String value) async {
    print('value---${value}');
    String cookie = await getCookie();
    // String baseUrl = 'http://117.72.52.18:9999/app/ai/chat';
    String baseUrl = 'http://111.228.34.63/app/ai/chat';
    String message = value;
    String responseText = '';
    String urlWithParams = '$baseUrl?message=$message';
    // 发起 SSE 请求，使用带参数的 URL
    SSEClient.subscribeToSSE(
      method: SSERequestType.GET,
      url: urlWithParams, // 传入带 message 参数的 URL
      header: {
        "Authorization": cookie,
        "Cookie": cookie,
        "Accept": "text/event-stream, application/json",
        "Cache-Control": "no-cache",
        "Content-Type": "application/json",
      },
    ).listen((event) {
      // print('Id: ' + event.id!);
      // print('Event: ' + event.event!);
      print('Data: ' + event.data!);
      var response = jsonDecode(event.data!);
      responseText += response['eventData'];
      print('responseText$responseText');
      if (event.data! != '') {
        _conversation[_conversation.length - 1]['content'] = responseText;
        dialogState(() {});
        WidgetsBinding.instance.addPostFrameCallback((_) {
          _scrollToBottom();
        });
      }
    });
  }

  void _requestFocus() {
    _focusNode.requestFocus();
  }

  List getBGC() {
    // 边界处理：如果数组长度小于2，返回空列表（避免报错）
    if (colorList.length < 2) {
      print('颜色数组长度不足2，无法获取两个不同值');
      return [];
    }

    final Random random = Random();
    // 第一次随机取索引（范围：0 ~ 数组长度-1）
    int firstIndex = random.nextInt(colorList.length);
    // 第二次随机取索引：确保与第一次不同（如果取到相同索引则重新取）
    int secondIndex;
    do {
      secondIndex = random.nextInt(colorList.length);
    } while (secondIndex == firstIndex);

    // 返回两个不同的颜色值
    return [colorList[firstIndex], colorList[secondIndex]];
  }

  // 根据item索引与当前页码的差值，计算该item的样式
  Matrix4 _buildSlideTransform(int index) {
    final double pageDiff = (_currentSlidePage - index).abs();
    // 中间项放大1.2倍，边缘项缩小（差值越大，缩放越小）
    final double scale = 1 - (pageDiff * 0.2); // 0.2是缩放差值（1 - 0.8 = 0.2）
    return Matrix4.identity()..scale(scale);
  }

  // 滑动的单个item构建（使用setList的渐变和标题）
  Widget _slideItem(item, int index) {
    final String verticalText = item['content'].split('').join('\n');
    return AnimatedBuilder(
      animation: _slideController,
      builder: (context, child) {
        // 计算透明度：中间项不透明，边缘项透明度0.6
        final double pageDiff = (_currentSlidePage - index).abs();
        final double opacity = 1 - (pageDiff * 0.4); // 0.4是透明度差值（1 - 0.6 = 0.4）

        return Opacity(
          opacity: opacity.clamp(0.6, 1.0), // 限制透明度在0.6~1.0之间
          child: Transform(
            transform: _buildSlideTransform(index),
            alignment: Alignment.center, // 以中心为原点缩放
            child: child,
          ),
        );
      },
      child: GestureDetector(
        // 可选：点击滑动项时选中（根据业务需求是否需要）
        onTap: () {
          setState(() {
            _selectedSlideItem = index;
          });
          // 点击后让当前item居中（优化体验）
          _slideController.animateToPage(
            index,
            duration: const Duration(milliseconds: 300),
            curve: Curves.ease,
          );
        },
        child: Container(
          width: 30.px,
          height: 200,
          margin: EdgeInsets.symmetric(horizontal: 8.px), // item之间的间距
          decoration: BoxDecoration(
            // 使用setList的渐变色
            gradient: LinearGradient(
              colors: [
                hexColor(item['color'][0]),
                hexColor(item['color'][1]),
              ],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
            borderRadius: BorderRadius.circular(32.px), // 圆角优化视觉
          ),
          alignment: Alignment.center,
          child: Text(
            verticalText,
            textDirection: TextDirection.rtl,
            style: TextStyle(
              fontSize: 32.px,
              color: hexColor('#333333'),
              fontWeight: FontWeight.w500,
            ),
            softWrap: true,
            textAlign: TextAlign.center, // 单个字在水平方向居中
          ),
        ),
      ),
    );
  }

  Widget inputBuild(width) {
    return Row(
      children: [
        Container(
          width: width * 0.8,
          height: 60.px,
          child: Focus(
            onFocusChange: (hafocus) {
              // 失去焦点
              if (!hafocus) {
                // SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersive);
                print('1${AIController.text}');
              }
            },
            child: TextField(
              controller: AIController, // 输入内容
              cursorColor: hexColor('#F04136'), // 光标颜色
              cursorWidth: 2.px, // 光标粗细
              focusNode: _focusNode,
              decoration: InputDecoration(
                filled: true,
                fillColor: Colors.white,
                contentPadding: EdgeInsets.only(bottom: 0, left: 8, top: 10),
                counterText: "",
                hintText: _isBottomSheetOpen ? '与AI讨论你的想法吧' : '输入你的目标吧',
                hintMaxLines: 1,
                focusedBorder: OutlineInputBorder(
                    // 输入框输入时的样式
                    borderSide: BorderSide(
                      color: hexColor('#cccccc'),
                      width: 1.px,
                    ),
                    borderRadius: BorderRadius.circular(16)),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: hexColor('#cccccc'), // 边框颜色
                    width: 1.px,
                  ),
                  borderRadius: BorderRadius.circular(16),
                ),
              ),
              maxLines: 1,
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w400,
              ),
            ),
          ),
        ),
        const SizedBox(width: 6),
        TextButton(
          style: TextButton.styleFrom(
            backgroundColor: const Color(0xFFE9614D),
            padding: const EdgeInsets.symmetric(horizontal: 10),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
          onPressed: () {
            _conversation
                .add({'role': 'user', 'content': AIController.text.trim()});
            _sendMessage();
            AIController.text = '';
            if (_isBottomSheetOpen) {
              WidgetsBinding.instance.addPostFrameCallback((_) {
                _scrollToBottom();
              });
            }
          },
          child: Text(
            _isBottomSheetOpen ? '发送' : '确认',
            style: const TextStyle(color: Colors.white),
          ),
        ),
      ],
    );
  }

  // 滑动区域整体构建
  Widget _slideSection() {
    return Column(
      children: [
        SizedBox(height: 40.px),
        // 滑动区域（核心）
        SizedBox(
          height: 460, // 滑动容器高度（需大于item高度，留出缩放空间）
          child: PageView.builder(
            controller: _slideController,
            itemCount: setList.length, // 滑动item数量（setList的长度）
            itemBuilder: (context, index) {
              return _slideItem(setList[index], index);
            },
            // 每次滑动一页（确保"每次滑动一个"的需求）
            pageSnapping: true,
          ),
        ),
        Padding(
          padding: EdgeInsets.only(top: 36),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 打开输入框
              GestureDetector(
                child: Container(
                  width: 38,
                  height: 38,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: hexColor('#E9614D'),
                    borderRadius: BorderRadius.circular(19),
                  ),
                  child: Text(
                    'Ai',
                    style: TextStyle(
                        color: hexColor('#FFFFFF'),
                        fontSize: 20,
                        fontWeight: FontWeight.bold),
                  ),
                ),
                onTap: () {
                  AIController.text = '';
                  _isBottomSheetOpen ? null : _openBottomSheet();
                },
              ),
              SizedBox(width: 20.px),
              // 确认按钮
              GestureDetector(
                child: Image.asset(
                  'lib/assets/images/home/sub.png',
                  width: 38,
                  height: 38,
                ),
                onTap: () {
                  if (_currentSlidePage.toInt() != _selectedSlideItem) {
                    _selectedSlideItem = _currentSlidePage.toInt();
                  }
                  HomeDataProvider.setTarget(setList[_selectedSlideItem]);
                  widget.callback!();
                  print('_currentSlidePage$_currentSlidePage');
                  print('_selectedSlideItem$_selectedSlideItem');
                  print('------${setList[_selectedSlideItem]}');
                },
              ),
            ],
          ),
        ),
        Padding(
            padding: EdgeInsets.only(top: 36, left: 30), child: inputBuild(340))
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          HeaderBack(
            title: HomeDataProvider.activeTab['title'] ?? '',
            isFirst: checkStep != 0,
            callback: () {
              checkStep = 0;
              setState(() {});
            },
          ),
          checkStep == 0
              ? Column(
                  children: [
                    Container(
                      width: 343,
                      padding: EdgeInsets.only(left: 26, top: 26),
                      child: dataList.isNotEmpty
                          ? Wrap(
                              spacing: 24,
                              children: [
                                ...dataList.map((it) {
                                  return SizedBox(
                                    width: 260.px,
                                    height: 130,
                                    child: dataItem(it),
                                  );
                                })
                              ],
                            )
                          : SizedBox(),
                    ),
                    TextButton(
                      onPressed: () {
                        if (active != 0) {
                          setState(() {
                            checkStep = 1;
                            getContent();
                          });
                        } else {
                          Toast.show(context: context, message: '请选择目标');
                        }
                      },
                      style: ButtonStyle(
                          backgroundColor:
                              MaterialStateProperty.all(hexColor('#E9614D'))),
                      child: Text(
                        '确定',
                        style: TextStyle(color: hexColor('#ffffff')),
                      ),
                    )
                  ],
                )
              : SingleChildScrollView(child: _slideSection())
        ],
      ),
    );
  }
}
